package com.ccys.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ccys.app.service.AppVersionService;
import com.ccys.app.service.SplashscreenService;
import com.ccys.common.util.Kit;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.SysCodeUtil;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.entity.TblMember;
import com.ccys.db.enums.GetMasterDataEnum;
import com.ccys.db.mapper.*;
import com.ccys.db.vo.app.splashscreen.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: WhiteCoat
 * @description: 进入屏幕时的接口实现
 * @author: ZhangJingCan
 * @create: 2024-01-15 11:55
 **/

@Service
public class SplashscreenServiceImpl implements SplashscreenService {


    @Autowired
    private AppVersionService appVersionService;

    /**
     * 用药周期
     */
    @Resource
    private TblMedicationUsagePeriodMapper tblMedicationUsagePeriodMapper;

    /**
     * 药物反应
     */
    @Resource
    private TblMedicationReactionMapper tblMedicationReactionMapper;

    /**
     * 国家
     */
    @Resource
    private TblCountryMapper tblCountryMapper;

    /**
     * 快递时间段
     */
    @Resource
    private TblDeliveryTimeSlotMapper tblDeliveryTimeSlotMapper;

    /**
     * 症状
     */
    @Resource
    private TblSymptomMapper tblSymptomMapper;

    /**
     * 计量单位
     */
    @Resource
    private TblUnitOfMeasurementMapper tblUnitOfMeasurementMapper;

    /**
     * 药品
     */
    @Resource
    private TblProductMapper tblProductMapper;

    /**
     * 用户
     */
    @Resource
    private TblMemberMapper tblMemberMapper;

    @Resource
    private TblBookingMapper tblBookingMapper;

    @Resource
    private TblDeliveryCountryMapper tblDeliveryCountryMapper;

    @Resource
    private TblPricingTimingMapper tblPricingTimingMapper;

    /**
     * 患者 -> 过敏 - 中间表
     */
    @Resource
    private TblMemberAllergiesMapper tblMemberAllergiesMapper;


    /**
     * 简介
     */
    @Resource
    private TblIntroductionMapper tblIntroductionMapper;

    /**
     * 问诊开药记录
     */
    @Resource
    private TblBookingPrescriptionMapper tblBookingPrescriptionMapper;


    @Override
    public ResponseResultApp<GetMasterDataVo> getMasterData(HttpServletRequest request) {
        //获取登录用户
        TblMember member = UserUtil.getCurLoginMember();
        //不存在则返回错误信息 - 指定错误代码为401
        if (ObjectUtil.isEmpty(member)) {
            return ResponseResultApp.error(401, "Request require authorization.");
        }
        //从请求头里面获取语言
        String language = request.getHeader("language");


        //准备返回对象
        //快递费用和是否有特快查询 - 快递类型:1:location-based;2:time-based
        //先查询tbl_delivery_country 快递设置表内，根据用户的国家ID去查询->dcDeliveryType=2,->存在->找tbl_delivery_time_slot的金额->
        //用户国家ID
        String countryOfResidence = member.getCurrentCountry();
        //用户国家的时区值
        Integer timezone = member.getCurrentCountryTimezone();
        //获取当前时间的时分字符串 - 根据当前时间以及时区值转换得来，返回是格式为：09:00
        String byTimeZone = Kit.getTimeStrByTimeZone(new Date(), timezone,"HH:mm");
        //快递信息查询
        GetMasterDataVo vo = tblDeliveryCountryMapper.getMasterDataFindExpressDelivery(countryOfResidence, byTimeZone);
        //设置咨询费
        vo.setConsultantFee(tblPricingTimingMapper.findValueByCountryIdAndByTime(countryOfResidence, byTimeZone));
        //检查一下如果为null - 设置为0
        if (ObjectUtil.isEmpty(vo.getConsultantFee())) {
            vo.setConsultantFee(new BigDecimal("0"));
        }

        //language 允许为空的 - 所以自己判断不为空
        if (ObjectUtil.isNotEmpty(language) && language.equals("en")) {
            vo.setExternalLink(GetMasterDataEnum.EXTERNAL_LINK_EN.getValue());
        } else if (ObjectUtil.isNotEmpty(language) && language.equals("vi")) {
            vo.setExternalLink(GetMasterDataEnum.EXTERNAL_LINK_VI.getValue());
        } else if (ObjectUtil.isNotEmpty(language) && language.equals("id")) {
            vo.setExternalLink(GetMasterDataEnum.EXTERNAL_LINK_ID.getValue());
        } else {
            //如果不传 - 取en的
            vo.setExternalLink(GetMasterDataEnum.EXTERNAL_LINK_EN.getValue());
        }
        //补充药物费用
        vo.setRefillMedicationFee(new BigDecimal(SysCodeUtil.getCode("Refill_Medication_Fee", "2").getValue()));
        //热线电话
        vo.setHotline(SysCodeUtil.getCode("Whc_hotline", "2").getValue());
        //已验证otp代码
        vo.setVerifiedOtpCode(SysCodeUtil.getCode("verified_otp_code", "1").getValue());
        //gst注册号
        vo.setGstRegNo(SysCodeUtil.getCode("gst_reg_no", "2").getValue());


        //设置版本号
        vo.setApp_versions(appVersionService.getAppVersion().getData());
        //应用内容
        vo.setAppContents(GetMasterDataEnum.APP_CONTENTS.getValue());
        //用药周期
        vo.setMedication_usage_periods(tblMedicationUsagePeriodMapper.getMasterDataFindList());
        //药物反应
        vo.setMedication_reactions(tblMedicationReactionMapper.getMasterFindList());
        //国家
        vo.setCountries(tblCountryMapper.getMasterDataFindList());
        //快递时间段
        vo.setTimeslots(tblDeliveryTimeSlotMapper.getMasterDataFindAllList());
        //症状
        vo.setSymptoms(tblSymptomMapper.getMasterDataFindAllList());
        //家庭关系 - 从枚举中取
        vo.setFamilyRelationships(GetMasterDataEnum.FAMILY_RELATIONSHIPS.getValue());
        //用药持续时间单位 - 从枚举中取
        vo.setMedicationDurationUnit(GetMasterDataEnum.MEDICATION_DURATION_UNIT.getValue());
        //计量单位 - tbl_unit_of_measurement 状态1 - 未删除 - 所有数据
        vo.setDosage_unit(tblUnitOfMeasurementMapper.getMasterDataFindAllList());
        //问候语 - 系统参数中拿
        vo.setAutomatedGreetingTbtc(SysCodeUtil.getCode("Textbased_Automated_Greeting_Tbtc", "2").getValue());
        //套接字运行状况检查（秒） - 系统参数
        vo.setSocketHealthCheckInSeconds(Integer.valueOf(SysCodeUtil.getCode("Socket_Health_Check_In_Seconds", "1").getValue()));
        //突发事件
        EmergencyMakeVo emergencyMakeVo = new EmergencyMakeVo();
        String statusStr = SysCodeUtil.getCode("AppEmergency_Status", "4").getValue();
        boolean status = statusStr.equals("true");
        emergencyMakeVo.setStatus(status);
        emergencyMakeVo.setRedirect(SysCodeUtil.getCode("AppEmergency_Redirect_URL", "4").getValue());
        emergencyMakeVo.setMessage(SysCodeUtil.getCode("AppEmergency_Message", "4").getValue());
        vo.setEmergency(emergencyMakeVo);
        vo.setPubnubPubkey(GetMasterDataEnum.PUBNUB_PUBKEY.getValue());
        vo.setPubnubSubkey(GetMasterDataEnum.PUBNUB_SUBKEY.getValue());
        //2FA - 系统参数获取
        Settings2FAMakeVo settings2FAMakeVo = new Settings2FAMakeVo();
        settings2FAMakeVo.setTurnOnOrOffLoginWith2fa(SysCodeUtil.getCode("Turn_On_Or_Off_Login_With_2FA", "2").getValue());
        settings2FAMakeVo.setTurnOnOrOf2fa(SysCodeUtil.getCode("Turn_On_Or_Off_2FA", "2").getValue());
        settings2FAMakeVo.setAmountOfTimePatientCanRemainOutOfApp(Integer.valueOf(SysCodeUtil.getCode("Amount_Of_Time_Patient_Can_Remain_Out_Of_App", "2").getValue()));
        settings2FAMakeVo.setTurnOnOrOffInactivitySessionIdle(SysCodeUtil.getCode("Turn_On_Or_Off_Inactivity_Session_Idle", "2").getValue());
        settings2FAMakeVo.setAmountOfTimeAppCanRemainAsIdle(Integer.valueOf(SysCodeUtil.getCode("Amount_Of_Time_App_Can_Remain_As_Idle", "2").getValue()));
        settings2FAMakeVo.setTimeoutResendPinCode(Integer.valueOf(SysCodeUtil.getCode("Time_Out_Resend_Pin_Code", "2").getValue()));
        vo.setSettings2FA(settings2FAMakeVo);
        //url
        String url = GetMasterDataEnum.AIA_EBEN_URL.getValue();
        vo.setAiaEbenUrl(url);
        vo.setAiaEbenV1Url(url + "?version=1");
        vo.setAiaEbenV2Url(url + "?version=2");
        vo.setAiaEbenAuthorization(GetMasterDataEnum.AIA_EBEN_AUTHORIZATION.getValue());
        String isTrueOrFalse = tblBookingMapper.getMasterDataFindCount(member.getId());
        vo.setRefillMedicationAllow(isTrueOrFalse);
        //为True才进入去查询 - 否则False直接设置为0
        if (isTrueOrFalse.equals("True")) {

        } else {
            vo.setRefillMedicationFee(new BigDecimal("0.0"));
        }
        //是否大于等于21岁
        Integer age = Kit.getAge(member.getDob());
        // 判断是否大于或等于21岁
        String is21OrOlder = (age >= 21) ? "True" : "False";
        //设置
        vo.setForChildThatTurned21(is21OrOlder);
        return ResponseResultApp.success(vo);
    }

    @Override
    public ResponseResultApp<List<GetMedicationVo>> getMedication() {
        TblMember member = UserUtil.getCurLoginMember();
        if (ObjectUtil.isEmpty(member)) {
            return ResponseResultApp.error(401, "Request require authorization.");
        }
        List<GetMedicationVo> list = tblProductMapper.findListProductAndPackageUnionAll();
        return ResponseResultApp.success(list);
    }

    @Override
    public ResponseResultApp<GetProfileVo> getProfile() {
        //获取当前用户
        TblMember member = UserUtil.getCurLoginMember();
        //不存在则返回错误信息 - 指定错误代码为401
        if (ObjectUtil.isEmpty(member)) {
            return ResponseResultApp.error(401, "Request require authorization.");
        }
        //准备返回对象
        GetProfileVo vo = new GetProfileVo();
        vo.setMemberId(member.getId());
        vo.setCode(member.getMemberNo());
        vo.setFirstName(member.getFirstName());
        vo.setLastName(member.getLastName() != null ? member.getLastName() : "");
        vo.setEmail(member.getEmail());
        vo.setNricFin(member.getNricFin());
        vo.setPhone(member.getPhone());
//        vo.setHomeAddress(member.getHomeAddress() != null ? member.getHomeAddress() : "");
//        vo.setOfficeAddress(member.getOfficeAddress() != null ? member.getOfficeAddress() : "");
        vo.setGender(member.getGender() == 0 ? "Female" : member.getGender() == 1 ? "Male" : member.getGender() == -1 ? "Not Specified" : "Unknown");
        vo.setGenderDb(member.getGender());
        vo.setDateOfBirth(member.getDob());
        vo.setAge(Kit.getAge(member.getDob()));
        vo.setRegDate(new Date(member.getCreatedOnUtc()));
        //回购次数
        vo.setRebuyCount(tblBookingPrescriptionMapper.findRebuyCountByMenberId(member.getId()));
        //国家ID
        vo.setCountryOfResidence(member.getCurrentCountry());
        vo.setLanguageCode(member.getCurrentLanguage());
        vo.setSingpassUuid(member.getSingpassUuid() != null ? member.getSingpassUuid() : "");
        vo.setNationality(member.getNationality() != null ? member.getNationality() : "");
        vo.setPhoneCountryId(member.getPhoneCountryId());
        vo.setEmergencyPhoneCountryId(member.getEmergencyCountryId() != null ? member.getEmergencyCountryId() : "");
        //个人资料照片
        vo.setProfilePhoto(member.getImage() != null ? member.getImage() : "");
        vo.setFrontIdentificationCardPhoto(member.getFrontIdentificationPhoto() != null ? member.getFrontIdentificationPhoto() : "");
        vo.setBackIdentificationCardPhoto(member.getBackIdentificationPhoto() != null ? member.getBackIdentificationPhoto() : "");
//        vo.setPassportPhoto(member.getPassport() != null ? member.getPassport() : "");
        vo.setPassportPhoto(member.getFrontIdentificationPhoto());
//        vo.setFrontOfDrivingLicensePhoto(member.getFrontDrivingLicense() != null ? member.getFrontDrivingLicense() : "");
//        vo.setBackOfDrivingLicensePhoto(member.getBackDrivingLicense() != null ? member.getBackDrivingLicense() : "");
        vo.setFrontOfDrivingLicensePhoto(member.getFrontIdentificationPhoto());
        vo.setBackOfDrivingLicensePhoto(member.getBackIdentificationPhoto());
        //1:NRIC_FIN 2:Passport 3:Birth_certificate 4:Driving_license 5:Child_photo
        vo.setTypeId(member.getType() == 1 ? "NRIC_FIN" : member.getType() == 2 ? "Passport" :
                member.getType() == 3 ? "Birth_certificate" : member.getType() == 4 ? "Driving_license" :
                        member.getType() == 5 ? "Child_photo" : "Unknown");
        vo.setEmergencyFirstName(member.getEmergencyFirstName() != null ? member.getEmergencyFirstName() : "");
        vo.setEmergencyLastName(member.getEmergencyLastName() != null ? member.getEmergencyLastName() : "");
        vo.setEmergencyPhone(member.getEmergencyPhone() != null ? member.getEmergencyPhone() : "");
        vo.setEmergencyRelationship(member.getEmergencyRelationship() != null ? member.getEmergencyRelationship() : "");
        vo.setEmergencyRelationshipId(member.getMemEmergencyRelationshipId());
        //是否大于等于21岁
        Integer age = Kit.getAge(member.getDob());
        // 判断是否大于或等于21岁
        vo.setForChildThatTurned21(age >= 21);
        vo.setG6pd(member.getG6pd() != null ? member.getG6pd() : null);
        //是否怀孕
        vo.setPregnant(ObjectUtil.isNotEmpty(member.getPregnant()) && member.getPregnant() == 1);
        //过敏症状 tblMemberAllergiesMapper 这里面有药物反应的id
        //这里查询了过敏以及药物反应的数据
        List<AllergiesAndMedicationReactionsMakeVo> allergiesAndMedicationReactionsMakeVos = tblMemberAllergiesMapper.findListAllergiesAndMedicationReactionsByMemberId(member.getId());
        //组装过敏以及药物反应
        List<AllergiesMakeVo> allergiesMakeVos = new ArrayList<>();
        List<MedicationReactionsMakeVo> medicationReactionsMakeVos = new ArrayList<>();
        Integer index = 0;
        for (AllergiesAndMedicationReactionsMakeVo makeVo : allergiesAndMedicationReactionsMakeVos) {
            //过敏数据组装
            AllergiesMakeVo allergiesMakeVo = new AllergiesMakeVo();
            allergiesMakeVo.setIndex(index);
            allergiesMakeVo.setId(makeVo.getAllergiesId());
            allergiesMakeVo.setName(makeVo.getAllergiesName());
            //加入集合
            allergiesMakeVos.add(allergiesMakeVo);

            //药物反应数据组装
            MedicationReactionsMakeVo medicationReactionsMakeVo = new MedicationReactionsMakeVo();
            medicationReactionsMakeVo.setId(makeVo.getMedicationReactionId());
            medicationReactionsMakeVo.setName(makeVo.getMedicationReactionName());
            medicationReactionsMakeVo.setIndex(index);
            //加入集合
            medicationReactionsMakeVos.add(medicationReactionsMakeVo);
            //索引++
            index++;
        }
        vo.setAllergies(allergiesMakeVos);
        //药物反应
        vo.setMedicationReactions(medicationReactionsMakeVos);
        //咨询地址
        ConsultAddressMakeVo addressMakeVo = new ConsultAddressMakeVo();
        addressMakeVo.setLocationAddress(member.getLocationAddress() != null ? member.getLocationAddress() : "");
        addressMakeVo.setLocationCountry(member.getLocationCountry() != null ? member.getLocationCountry() : "");
        addressMakeVo.setLocationPostalCode(member.getLocationPostalCode() != null ? member.getLocationPostalCode() : "");
        addressMakeVo.setLocationLatitude(member.getLocationLatitude() != null ? member.getLocationLatitude() : new BigDecimal("0.0"));
        addressMakeVo.setLocationLongitude(member.getLocationLongitude() != null ? member.getLocationLongitude() : new BigDecimal("0.0"));
        addressMakeVo.setLocationFloorNumber(member.getLocationFloorNumber() != null ? member.getLocationFloorNumber() : "");
        addressMakeVo.setLocationDetailAddress(member.getLocationDetailAddress() != null ? member.getLocationDetailAddress() : "");
        addressMakeVo.setLocationCity(member.getLocationCity() != null ? member.getLocationCity() : "");
        addressMakeVo.setLocationState(member.getLocationState() != null ? member.getLocationState() : "");
        vo.setConsultAddress(addressMakeVo);
        vo.setPendingNric(member.getPendingNric() != null ? member.getPendingNric() : "");
        //是否保持登录状态
        vo.setStayLoggedIn(ObjectUtil.isNotEmpty(member.getMemStayLoggedIn()) && member.getMemStayLoggedIn());

        //设置当前时间段最高的问诊费用
        //用户国家的时区值
        Integer timezone = member.getCurrentCountryTimezone();
        //获取当前时间 - 通过时区转换的时间 例如：08:30 字符串
        String timeStr = Kit.getTimeStrByTimeZone(new Date(), timezone,"HH:mm");
        //获取当前星期几，注意0-星期一，以此类推6-星期天
        int dayOfTheWeek = Kit.getWhatDayIsToday(timezone);
        vo.setIndividualConsultFee(tblPricingTimingMapper.findMaxFeeByTime(timeStr, member.getCurrentCountry(), dayOfTheWeek));


        return ResponseResultApp.success(vo);
    }

    @Override
    public ResponseResultApp<List<GetIntroPagesMakeVo>> GetIntroPages() {
        //todo:这里未校验 - 并且对方接口连active - 状态都返回了 - 意味着启不启用的数据都返回？
        //todo:注意这个SQL里面没有限制只查询status=1,只限制了未删除
        List<GetIntroPagesMakeVo> list = tblIntroductionMapper.findList();
        return ResponseResultApp.success("Sukses", list);
    }

    public static void main(String[] args) throws Exception {
//        String s = Kit.getTimeByTimeZone(new Date(), 8);
//        System.out.println("时间转换后的时分：" + s);
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date parse = format.parse("2020-01-16 08:00:00");
//        Integer age = Kit.getAge(parse);
//        System.out.println("年龄：" + age);
    }


}
